package cn.seaboot.admin.file.image;

import cn.seaboot.admin.images.bean.SysImage;
import cn.seaboot.admin.images.service.SysImageService;
import cn.seaboot.commons.core.Asserts;
import cn.seaboot.commons.file.ResponseWriter;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件管理
 *
 * @author Mr.css
 * @version 2023-07-05 15:35
 */
@Service
public class ImageManager {

    @Resource
    private SysImageService sysImageService;


    /**
     * 文件下载
     *
     * @param file 文件对象实体
     */
    public SysImage upload(Integer type, @NotNull MultipartFile file) throws IOException {
        Asserts.notNull(file, "File is undefined!");
        return sysImageService.upload(type, file);
    }

    /**
     * 文件查看
     *
     * @param request  -
     * @param response -
     * @param id       -
     */
    public void preview(HttpServletRequest request, HttpServletResponse response, Long id) throws IOException {
        SysImage image = sysImageService.queryById(id);
        if (image == null) {
            response.getWriter().write("File not found!");
        } else {
            try (InputStream is = sysImageService.openInputStream(image.getImagePath())) {
                ResponseWriter.preview(response, is, image.getImageName());
            }
        }
    }

    /**
     * 文件下载
     *
     * @param request  -
     * @param response -
     * @param id       -
     */
    public void download(HttpServletRequest request, HttpServletResponse response, Long id) throws IOException {
        SysImage image = sysImageService.queryById(id);
        if (image == null) {
            response.getWriter().write("File not found!");
        } else {
            try (InputStream is = sysImageService.openInputStream(image.getImagePath())) {
                ResponseWriter.download(response, is, image.getImageName());
            }
        }
    }
}
